﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DFGK_WMS.Model.Helper
{
    public enum HttpRequestType
    {
        Get,
        Post,
        Put,
        Delete
    }
    public class ApiResponse<T>
    {
        public T Data { get; set; }
        public string Code { get; set; }
        public string Message { get; set; }
        public int Count { get; set; }
        public bool Success { get; set; }
    }
    public class HttpHelper
    {
        private readonly string _baseUrl;

        public HttpHelper(string baseUrl)
        {
            _baseUrl = baseUrl;
        }
        /// <summary>
        /// 发送http请求
        /// </summary>
        /// <typeparam name="T">Data的类型</typeparam>
        /// <param name="requestType">枚举 访问方式 get post put delete</param>
        /// <param name="url">接口地址 会拼在baseUrl后面</param>
        /// <param name="requestData">入参 可为空 如果空传null</param>
        /// <param name="token">tokne 可为空 如果空传null</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task<(bool Success, ApiResponse<T> ResponseData)> SendRequest<T>(HttpRequestType requestType,
            string url, object? requestData, string? token)
        {
            string fullUrl = _baseUrl + url;

            // 创建 HttpClient 实例
            using var client = new HttpClient();

            // 添加 Authorization 请求头，携带 token
            if (!string.IsNullOrEmpty(token))
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }

            // 根据请求类型执行相应的操作
            HttpResponseMessage response;
            switch (requestType)
            {
                case HttpRequestType.Get:
                    // 将查询参数拼接到 URL 中
                    string queryString = ToQueryString(requestData);
                    if (!string.IsNullOrEmpty(queryString))
                    {
                        fullUrl += "?" + queryString;
                    }
                    response = await client.GetAsync(fullUrl);
                    break;
                case HttpRequestType.Post:
                    if (requestData == null)
                    {
                        response = await client.PostAsync(fullUrl, null);
                    }
                    else
                    {
                        var requestDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                        await Console.Out.WriteLineAsync(JsonConvert.SerializeObject(requestData));
                        response = await client.PostAsync(fullUrl, requestDataJson);
                    }

                    break;
                case HttpRequestType.Put:
                    // 在实际应用中根据需要添加请求数据
                    if (requestData == null)
                    {
                        response = await client.PutAsync(fullUrl, null);
                    }
                    else
                    {
                        var putDataJson = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
                        response = await client.PutAsync(fullUrl, putDataJson);
                    }
                    break;
                case HttpRequestType.Delete:
                    // 将查询参数拼接到 URL 中
                    string deleteQueryString = ToQueryString(requestData);
                    if (!string.IsNullOrEmpty(deleteQueryString))
                    {
                        fullUrl += "?" + deleteQueryString;
                    }
                    response = await client.DeleteAsync(fullUrl);
                    break;
                default:
                    throw new ArgumentException("Invalid request type.");
            }

            // 检查响应是否成功
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容并进行适当的转换
                ApiResponse<T> responseData = await response.Content.ReadFromJsonAsync<ApiResponse<T>>();
                return (true, responseData);
            }
            else
            {
                // 响应失败，设置默认值并返回 false
                return (false, default);
            }
        }

        private string ToQueryString(object requestParams)
        {
            if (requestParams == null)
            {
                return string.Empty;
            }

            var properties = from p in requestParams.GetType().GetProperties()
                             where p.GetValue(requestParams, null) != null
                             select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(requestParams, null).ToString());

            return string.Join("&", properties.ToArray());
        }


    }
}
